package smscode

import (
	"encoding/json"
	"fmt"
	"multimedia/utils"
	"net/url"

	log "github.com/sirupsen/logrus"
)

func SendSms(phone_area string, phone_num string, resqId string) (string, string) {
	datacode := utils.Get6bitRandomDigit()
	urlValues := url.Values{}
	urlValues.Add("Apikey", "6544075c932f43433117604d68c97a28")
	urlValues.Add("Username", "ZYZX-DXDY-YKF-5GSP")
	urlValues.Add("Billid", phone_num)
	urlValues.Add("Rspid", resqId)
	infomap := fmt.Sprintf("{\"data_code\":%s}", datacode)
	urlValues.Add("InfoMap", infomap)
	uri := "https://117.159.206.250:20080/sendtempsms"
	reqData := urlValues.Encode()

	log.WithField("func", "SendSms").Infof("msg is:%s %v", reqData, infomap)

	body, err := utils.HttpPostFormReq(uri, "application/x-www-form-urlencoded", reqData)
	if err != nil {
		return "", err.Error()
	}
	SMSRes := utils.SmsRes{}
	err = json.Unmarshal(body, &SMSRes)
	if err != nil {
		return "", err.Error()
	}
	if SMSRes.Returncode != "200" {
		return "", SMSRes.Returnmessage
	}
	return datacode, ""
}

func SendCode(phone_area string, phone_num string, resqId string, msg string) string {
	urlValues := url.Values{}
	urlValues.Add("Apikey", "6544075c932f43433117604d68c97a28")
	urlValues.Add("Username", "ZYZX-DXDY-YKF-5GSP")
	urlValues.Add("Billid", phone_num)
	urlValues.Add("Rspid", resqId)
	infomap := utils.InfoMap{}
	infomap.DataCode = msg
	infostr, err := json.Marshal(infomap)
	if err != nil {
		return err.Error()
	}
	urlValues.Add("InfoMap", string(infostr))

	uri := "https://117.159.206.250:20080/sendtempsms"
	reqData := urlValues.Encode()
	log.WithField("func", "SendCode").Infof("msg is:%s %v", reqData, infostr)

	body, err := utils.HttpPostFormReq(uri, "application/x-www-form-urlencoded", reqData)
	if err != nil {
		return err.Error()
	}
	SMSRes := utils.SmsRes{}
	err = json.Unmarshal(body, &SMSRes)
	if err != nil {
		return err.Error()
	}
	if SMSRes.Returncode != "200" {
		return SMSRes.Returnmessage
	}
	return ""
}

// //发送注册短信
// func SendSmsRegister(phone_area string, phone_num string) string {
// 	respCode := SendSms(phone_area, phone_num, utils.MsgType_Login)
// 	return respCode
// }

// //发送修改密码短信
// func SendSmsModifyPwd(phone_area string, phone_num string) string {
// 	respCode := SendSms(phone_area, phone_num, utils.MsgType_ModifyPwd)
// 	return respCode
// }

// //忘记密码
// func SendSmsForgetPwd(phone_area string, phone_num string) string {
// 	respCode := SendSms(phone_area, phone_num, utils.MsgType_ForgetPwd)
// 	return respCode
// }

// func RandSmsCode() string {
// 	return fmt.Sprintf("%04d", rand.New(rand.NewSource(time.Now().UnixNano())).Int31n(9000)+1000)
// }
